<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import utils from '@/utils/utils.js'

const loading = ref(true)
//   获取Composition API 上下文对象
const { ctx } = getCurrentInstance()
// 获取全局挂载的属性
const { $api, $message } =
  getCurrentInstance().appContext.config.globalProperties
const action = ref('create')
// 权限列表
const roleList = ref([])
// 菜单列表
const menuList = ref([])

// 表单数据对象
const queryForm = reactive({
  roleName: ''
})

const roleForm = reactive({})

const pager = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 10
})
// 表单列数据
const columns = reactive([
  {
    label: '角色名称',
    prop: 'roleName',
    width: 150
  },
  {
    label: '备注',
    prop: 'remark',
    width: 150
  },
  {
    label: '权限列表',
    prop: 'permissionList',
    width: 250,
    formatter: (row, column, value) => {
      // console.log(value)
      let names = []
      let list = value.halfCheckedKeys || []
      // 获取了父节点的value值
      // console.log(actionMap.value)
      list.map((key) => {
        let name = actionMap.value[key]
        if (key && name) names.push(name)
      })
      return names.join(',')
    }
  },
  {
    label: '创建时间',
    prop: 'createTime',
    width: 300,
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value))
    }
  }
])

// dialog弹出框初始值
const showPermission = ref(false)
const showModel = ref(false)
const curRoleName = ref('')
const curRoleId = ref('')
// 菜单映射表
const actionMap = reactive({})

// 表单定义规则
const rules = reactive({
  roleName: [
    {
      required: true,
      message: '请输入角色名称',
      trigger: 'blur'
    }
  ]
})

onMounted(() => {
  getRoleList()
  getMenuList()
})

// 角色列表初始化
const getRoleList = async () => {
  try {
    let { list, page } = await $api.getRoleList({
      ...queryForm,
      ...pager
    })
    // console.log(list)
    roleList.value = list
    pager.total = page.total
    setTimeout(() => {
      loading.value = false
    }, 300)
    // console.log(menuList)
  } catch (error) {
    throw new Error(error)
  }
}
// 菜单列表初始化
const getMenuList = async () => {
  try {
    let list = await $api.getMenuList()
    menuList.value = list
    getActionMap(list)
  } catch (error) {
    throw new Error(error)
  }
}

// 递归遍历key值转换为字典
const getActionMap = (list) => {
  // console.log(list)
  let actionMapNew = {}
  const deep = (arr) => {
    // console.log(arr)
    while (arr.length) {
      // pop() 方法从数组中删除最后一个元素,并返回该元素的值(此方法修改该数组的长度)
      // 获取数组中的id
      let item = arr.pop()
      // console.log(item)
      if (item.children && item.action) {
        actionMapNew[item._id] = item.menuName
      }
      // 存在item.children但不存在item.action继续执行递归
      if (item.children && !item.action) {
        deep(item.children)
      }
    }
  }
  deep(JSON.parse(JSON.stringify(list)))
  actionMap.value = actionMapNew
  console.log(actionMap)
}

// 表单重置
const handleReset = (form) => {
  ctx.$refs[form].resetFields()
}

// 角色编辑
const handleEdit = (row) => {
  console.log(row)
  action.value = 'edit'
  showModel.value = true
  ctx.$nextTick(() => {
    let params = {}
    params.roleName = row.roleName
    params.remark = row.remark
    params._id = row._id
    Object.assign(roleForm, params)
  })
}

// 角色添加
const handleAdd = () => {
  showModel.value = true
  action.value = 'create'
  getRoleList()
}

// 角色删除
const handleDel = async (_id) => {
  await $api.roleOperate({ _id, action: 'delete' })
  $message.success('删除成功')
  getRoleList()
}

// 表单提交
const handleSubmit = () => {
  ctx.$refs.dialogForm.validate(async (valid) => {
    if (valid) {
      // console.log(valid)
      let params = { ...roleForm }
      params.action = action.value
      console.log(params)
      let res = await $api.roleOperate(params)
      console.log(res)
      if (res) {
        showModel.value = false
        $message.success('创建成功')
        handleReset('dialogForm')
        getRoleList()
      }
    }
  })
}

// 关闭弹出框
const handleClose = () => {
  handleReset('dialogForm')
  showModel.value = false
}

// 设置权限
const handleOpenPermission = (row) => {
  // console.log(row)
  curRoleId.value = row._id
  curRoleName.value = row.roleName
  showPermission.value = true
  let { checkedKeys } = row.permissionList
  ctx.$nextTick(() => {
    ctx.$refs.permissionTree.setCheckedKeys(checkedKeys)
  })
}

// 提交权限表单
const handlePermissionSubmit = async () => {
  // 获取整个节点
  let nodes = ctx.$refs.permissionTree.getCheckedNodes()
  console.log(nodes)
  let halfKeys = ctx.$refs.permissionTree.getHalfCheckedKeys()
  let checkedKeys = []
  let parentKeys = []
  nodes.map((node) => {
    if (!node.children) {
      checkedKeys.push(node._id)
    } else {
      parentKeys.push(node._id)
    }
  })
  // console.log(checkedKeys)
  let params = {
    _id: curRoleId.value,
    permissionList: {
      checkedKeys,
      // 拼接例如系统管理下的用户管理模块
      halfCheckedKeys: parentKeys.concat(halfKeys)
    }
  }

  await $api.updatePermission(params)
  // console.log(res)
  showPermission.value = false
  $message.success('设置成功')
  getRoleList()
}
// 页数
const handleCurrentChange = (current) => {
  pager.pageNum = current
  getRoleList()
}
</script>
<template>
  <div class="role-manage">
    <!-- 搜索视图 -->
    <el-card class="box-card">
      <el-form ref="form" :inline="true" :model="queryForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入角色名称" v-model="queryForm.roleName" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRoleList" size="default"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button ize="default" @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="base-table">
      <el-form :inline="true" class="demo-form-inline action">
        <el-form-item>
          <el-button type="primary" @click="handleAdd" size="default"
            >创建</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :highlight-current-row="true"
        :data="roleList"
        v-loading="loading"
      >
        <el-table-column
          style="text-align: center"
          v-for="item in columns"
          :prop="item.prop"
          :key="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
          align="left"
        ></el-table-column>
        <el-table-column label="操作" width="500" align="left">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleOpenPermission(scope.row)"
              >设置权限</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDel(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next,jumper"
          :total="parseInt(pager.total)"
          :page-size="pager.pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 用户新增弹框 -->
    <el-dialog title="用户新增" v-model="showModel">
      <el-form
        label-width="120px"
        ref="dialogForm"
        :model="roleForm"
        :rules="rules"
      >
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="roleForm.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleSubmit">确 认</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限弹框 -->
    <el-dialog title="权限设置" v-model="showPermission">
      <el-form label-wdith="100px">
        <el-form-item label="角色名称">
          {{ curRoleName }}
        </el-form-item>
        <el-form-item label="选择权限">
          <el-tree
            ref="permissionTree"
            :data="menuList"
            show-checkbox
            node-key="_id"
            default-expand-all
            :props="{ label: 'menuName' }"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermission = false">取 消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit"
            >确 认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.box-card {
  margin-top: 25px;
}
.pagination {
  margin-top: 1.5rem;
  display: flex;
  justify-content: end;
}
</style>
